package com.pansoft.openplanet.fragment;

import android.os.Bundle;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.ContextMenu;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.efounder.chat.http.JFCommonRequestManager;
import com.efounder.constant.EnvironmentVariable;
import com.efounder.frame.baseui.BaseFragment;
import com.efounder.util.AppContext;
import com.efounder.util.ToastUtil;
import com.efounder.utils.JfResourceUtil;
import com.efounder.utils.ResStringUtil;
import com.google.gson.Gson;
import com.pansoft.kline.activity.TransactionTrendActivity;
import com.pansoft.kline.greendao.DaoSessionUtil;
import com.pansoft.kline.model.ConfigCoinBean;
import com.pansoft.kline.model.ConfigMarketBean;
import com.pansoft.kline.model.ConfigSiteBean;
import com.pansoft.kline.model.MarketMenuBean;
import com.pansoft.kline.model.SelfSelectRefreshEvent;
import com.pansoft.kline.model.SelfSelectedBean;
import com.pansoft.kline.util.BtcKanNumberFormatUtil;
import com.pansoft.kline.util.KLineUtil;
import com.pansoft.kline.util.MarketNumberUtils;
import com.pansoft.kline.util.SelfSelectUtils;
import com.pansoft.openplanet.R;
import com.pansoft.openplanet.adapter.BtckanDetailAdapter;
import com.pansoft.openplanet.bean.BtcKanDetailsRemoteKindCoinsBean;
import com.pansoft.openplanet.bean.BtckanDetailBean;
import com.pansoft.openplanet.manager.CurrencyAndBourseManager;
import com.pansoft.openplanet.util.TCMathUtil;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.MediaType;
import okhttp3.RequestBody;

import static com.pansoft.openplanet.constant.MarketConstant.MARKET_KIND_COINS_URL;

/**
 * 币看详情页面
 *
 * @author cimu
 * @date 2018/11/7
 */

public class BtckanDetailFragment extends BaseFragment {
    public static final String TAG = "BtckanDetailFragment";
    private View mView;
    private TextView tvRmbPhoto, tvWbPrice, tvWbPhoto, tvPercentage;
    private TextView tvSiteName;
    private TextView tvHigh;
    private TextView tvRmbPrice;
    private TextView tvLow;
    private TextView tvAmount;


    private RecyclerView recyclerView;
    private BtckanDetailAdapter mBtckanDetailAdapter;
    private SmartRefreshLayout mRefreshLayout;
    private List<BtckanDetailBean> btckanDetailBeans = new ArrayList<>();

    //上一次的数据用来做对比使用
    List<BtcKanDetailsRemoteKindCoinsBean.DataBean.TickersBean> lastTicherList = new ArrayList<>();
    private Timer timer;
    private RefreshTask timerTask;
    private MarketMenuBean.DataBean.CategoryBean.ListBean menuBean;

    private String kindCoinsName;
    private boolean isOndestroyView = false;
    /** 顶部item的市场id**/
    private String topItemMarketId;
    //当前货币code 如CNY USD
    private String currencyCode;

    public static BtckanDetailFragment newInstance(MarketMenuBean.DataBean.CategoryBean.ListBean bean) {
        BtckanDetailFragment fragment = new BtckanDetailFragment();
        Bundle args = new Bundle();
        args.putSerializable("bean", bean);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mView = LayoutInflater.from(getActivity()).inflate(R.layout.assets_fragment_btckan_detail, container, false);
        initView();
        initParam();
        registerForContextMenu(recyclerView);
        return mView;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (getUserVisibleHint() == true) {
            startTask();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        stopTask();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        stopTask();
        isOndestroyView = true;
    }

    private void initView() {
        tvRmbPhoto = mView.findViewById(R.id.rmb_photo);
        tvWbPrice = mView.findViewById(R.id.wb_price);
        tvWbPhoto = mView.findViewById(R.id.wb_photo);
        tvPercentage = mView.findViewById(R.id.percentage);

        tvSiteName = (TextView) mView.findViewById(R.id.tv_site_name);
        tvHigh = (TextView) mView.findViewById(R.id.tv_high);
        tvRmbPrice = (TextView) mView.findViewById(R.id.tv_rmb_price);
        tvLow = (TextView) mView.findViewById(R.id.tv_low);
        tvAmount = (TextView) mView.findViewById(R.id.tv_amount);
        mRefreshLayout = mView.findViewById(R.id.rfl_btckan);

        mRefreshLayout.setEnableLoadMore(false);

        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                stopTask();
                remoteKindsCoins(true);

            }
        });
        mView.findViewById(R.id.ll_top_item).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (topItemMarketId != null && !"".equals(topItemMarketId)) {
                    TransactionTrendActivity.start(getActivity(), topItemMarketId);
                }
            }
        });
        mView.findViewById(R.id.ll_top_item).setOnCreateContextMenuListener(new View.OnCreateContextMenuListener() {
            @Override
            public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
                long id = SelfSelectUtils.getIsSelectedId(topItemMarketId);
                if (id != -1) {
                    menu.add(0, v.getId(), 3000, ResStringUtil.getString(R.string.chart_delete_self_selected));
                } else {
                    menu.add(0, v.getId(), 3000, ResStringUtil.getString(R.string.chart_add_to_self_selected));
                }
            }
        });
        recyclerView = mView.findViewById(R.id.rv_btckan);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        recyclerView.setLayoutManager(linearLayoutManager);
        mBtckanDetailAdapter = new BtckanDetailAdapter(getActivity(), btckanDetailBeans);
        recyclerView.setAdapter(mBtckanDetailAdapter);
        //remoteKindsCoins(false);

    }

    private void initParam() {
        currencyCode = CurrencyAndBourseManager.getCurrencyUnitCode();
        isOndestroyView = false;
        menuBean = (MarketMenuBean.DataBean.CategoryBean.ListBean) getArguments().getSerializable("bean");
        kindCoinsName = menuBean.getId();
        mRefreshLayout.autoRefresh();

    }

    /**
     * 开始定时刷新任务
     */
    private void startTask() {
        if (getUserVisibleHint() == false) {
            stopTask();
            return;
        }
        if (isOndestroyView) {
            return;
        }
        stopTask();
        timer = new Timer();
        timerTask = new RefreshTask();
        timer.schedule(timerTask, 0, 5000);
    }

    /**
     * 结束定时刷新任务
     */
    private void stopTask() {
        if (timer != null) {
            timer.cancel();
            timer.purge();
            timer = null;
            timerTask = null;
        }
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

        if (mView != null) {
            if (isVisibleToUser) {
                startTask();
            } else {
                stopTask();
            }
        }
    }


    public class RefreshTask extends TimerTask {

        @Override
        public void run() {
//            LogUtils.i(menuBean.getTitle(), "执行RefreshTask");
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    remoteKindsCoins(false);
                }
            });
        }
    }

    /**
     * 从服务器请求数据
     *
     * @param isRefresh 是否是下拉刷新
     */
    private void remoteKindsCoins(final boolean isRefresh) {
        HashMap<String, String> hashMap = new HashMap<>();
        MediaType JSON = MediaType.parse("application/json; charset=utf-8");
        hashMap.put("categoryID", kindCoinsName);
        JSONObject jsonObject;
        try {
            jsonObject = new JSONObject(hashMap.toString());
            RequestBody requestBody = RequestBody.create(JSON, jsonObject.toString());

            JFCommonRequestManager.getInstance(getActivity()).requestPostByAsyncWithRequsetBody(TAG,
                    MARKET_KIND_COINS_URL, requestBody, new JFCommonRequestManager.ReqCallBack<String>() {
                        @Override
                        public void onReqSuccess(String result) {
                            if (isRefresh) {
                                mRefreshLayout.finishRefresh(100);
                                startTask();
                            }
                            try {
                                BtcKanDetailsRemoteKindCoinsBean kindCoinsBean = new Gson().fromJson(result, BtcKanDetailsRemoteKindCoinsBean.class);
                                if (kindCoinsBean.getCode() != 0) {
                                    ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                                    return;
                                }
                                refreshData(kindCoinsBean);
                            } catch (Exception e) {
                                e.printStackTrace();
                                ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail);
                            }
                        }


                        @Override
                        public void onReqFailed(String errorMsg) {
                            ToastUtil.showToast(AppContext.getInstance(), R.string.common_text_http_request_fail_abnormal);
                            if (isRefresh) {
                                mRefreshLayout.finishRefresh(100);

                                startTask();
                            }
                        }
                    });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 刷新界面数据
     *
     * @param kindCoinsBean
     * @throws Exception
     */
    private void refreshData(BtcKanDetailsRemoteKindCoinsBean kindCoinsBean) throws Exception {
        List<BtcKanDetailsRemoteKindCoinsBean.DataBean.TickersBean> tickersBeans = kindCoinsBean.getData().getTickers();
        if (lastTicherList.size() == 0) {
            lastTicherList.addAll(tickersBeans);
        }
        btckanDetailBeans.clear();

        for (int i = 0; i < tickersBeans.size(); i++) {
            //新数据
            BtcKanDetailsRemoteKindCoinsBean.DataBean.TickersBean itemBean = tickersBeans.get(i);
            //上一次数据
            BtcKanDetailsRemoteKindCoinsBean.DataBean.TickersBean lastItemBean = lastTicherList.get(i);

            String marketId = itemBean.getId();
            ConfigMarketBean marketBean = null;
            ConfigCoinBean coinBean = null;
            ConfigSiteBean siteBean = null;
            try {
                marketBean = DaoSessionUtil.getInstance().getConfigMarketBeanDao().load(marketId);
                coinBean = DaoSessionUtil.getInstance().getConfigCoinBeanDao().load(marketBean.getCoin());
                siteBean = DaoSessionUtil.getInstance().getConfigSiteBeanDao().load(marketBean.getSite());
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }

            String siteName = siteBean.getTitle() + "," + coinBean.getTitle();
            String currency = marketBean.getCurrency();

            BtckanDetailBean btckanDetailBean = new BtckanDetailBean();

            //设置交易所id
            btckanDetailBean.setMarketId(marketId);
            //rmb 价格 取last * 汇率
            btckanDetailBean.setLast(tickersBeans.get(i).getLast());
            btckanDetailBean.setSiteName(siteName);
            btckanDetailBean.setSite(marketBean.getSite());
            //货币单位
            btckanDetailBean.setCurrency(currency);
            //左侧的量。。万
            btckanDetailBean.setLeftAmount(itemBean.getVol());

            //对比大小
//            if (lastItemBean.getLast() == itemBean.getLast()) {
//                btckanDetailBean.setTrendType(0);
//            } else
            if (itemBean.getLast() > lastItemBean.getLast()) {
                btckanDetailBean.setTrendType(1);
                itemBean.setLastTrendType(1);
            } else if (lastItemBean.getLast() > itemBean.getLast()) {
                btckanDetailBean.setTrendType(-1);
                itemBean.setLastTrendType(-1);
            } else {
                btckanDetailBean.setTrendType(lastItemBean.getLastTrendType());
                itemBean.setLastTrendType(lastItemBean.getLastTrendType());
            }


            if (i == 0) {
                setTopData(itemBean, marketBean, coinBean, siteBean, btckanDetailBean);
            } else {
                btckanDetailBeans.add(btckanDetailBean);
            }
        }

        lastTicherList.clear();
        lastTicherList.addAll(tickersBeans);
        mBtckanDetailAdapter.notifyDataSetChanged();

    }

    /**
     * 设置第一条的数据
     *
     * @param itemBean
     * @param marketBean
     * @param coinBean
     * @param siteBean
     * @param btckanDetailBean
     */
    private void setTopData(BtcKanDetailsRemoteKindCoinsBean.DataBean.TickersBean itemBean,
                            ConfigMarketBean marketBean, ConfigCoinBean coinBean, ConfigSiteBean siteBean,
                            BtckanDetailBean btckanDetailBean) throws Exception {
        String siteName = siteBean.getTitle() + "," + coinBean.getTitle() + "," + marketBean.getCurrency();
        topItemMarketId = btckanDetailBean.getMarketId();
        double high = itemBean.getHigh();
        double low = itemBean.getLow();
        double last = itemBean.getLast();
        double open = itemBean.getOpen();

//        String rmbRate = BtcKanConfigAndRateHelper.getRate(null).getJSONObject(siteBean.getUniqueKey()).getString("CNY");
//        String otherRate = BtcKanConfigAndRateHelper.getRate(null).getJSONObject(siteBean.getUniqueKey()).getString(marketBean.getCurrency());

//        high = TCMathUtil.bigFormat(TCMathUtil.mul(high + "", rmbRate), 5);
//        low = TCMathUtil.bigFormat(TCMathUtil.mul(low + "", rmbRate), 5);

        high = MarketNumberUtils.getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), currencyCode, high);
        low = MarketNumberUtils.getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), currencyCode, low);
        tvHigh.setText(BtcKanNumberFormatUtil.assignNumberFormat(high, 6, 6) + "");
        tvLow.setText(BtcKanNumberFormatUtil.assignNumberFormat(low, 6, 6) + "");


        tvSiteName.setText(siteName);


//        tvLow.setText(low + "");
        tvAmount.setText(MarketNumberUtils.amountConversion(itemBean.getVol()));

        //rmb 价格 取last * 汇率
//        double rmbPrice = TCMathUtil.bigFormat(TCMathUtil.mul(last + "", rmbRate), 5);

        double rmbPrice = MarketNumberUtils.getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), currencyCode, last);
        tvRmbPrice.setText(BtcKanNumberFormatUtil.assignNumberFormat(rmbPrice, 7, 5) + "");
        tvRmbPhoto.setText(CurrencyAndBourseManager.getNowCurrencySymbol());
        //left 下方价格
//        double otherPrice = TCMathUtil.bigFormat(TCMathUtil.mul(itemBean.getLast() + "", otherRate), 5);
        double otherPrice = MarketNumberUtils.getRealPrice(siteBean.getUniqueKey(), marketBean.getCurrency(), marketBean.getCurrency(), last);
        tvWbPrice.setText(BtcKanNumberFormatUtil.assignNumberFormat(otherPrice, 7, 5) + "");
        tvWbPhoto.setText(KLineUtil.getCurrencySymbol(marketBean.getCurrency()));


        //百分比使用 last open 计算
        double balance = TCMathUtil.sub(last, open);
        String percent = BtcKanNumberFormatUtil.getPercent(TCMathUtil.div(balance, open, 4));
        tvPercentage.setText(BtcKanNumberFormatUtil.addNumberSign(percent));
        if (percent.contains("-")) {
            tvPercentage.setTextColor(JfResourceUtil.getSkinColor(R.color.decreasing_color));
        } else {
            tvPercentage.setTextColor(JfResourceUtil.getSkinColor(R.color.increasing_color));
        }

        //设置字体颜色
        if (btckanDetailBean.getTrendType() == 0) {
            tvRmbPrice.setTextColor(JfResourceUtil.getSkinColor(R.color.chart_main_white_or_black));
            tvRmbPhoto.setTextColor(JfResourceUtil.getSkinColor(R.color.chart_main_white_or_black));
            tvWbPhoto.setTextColor(JfResourceUtil.getSkinColor(R.color.black_text_color));
            tvWbPrice.setTextColor(JfResourceUtil.getSkinColor(R.color.black_text_color));
        } else if (btckanDetailBean.getTrendType() == 1) {
            tvRmbPrice.setTextColor(JfResourceUtil.getSkinColor(R.color.increasing_color));
            tvRmbPhoto.setTextColor(JfResourceUtil.getSkinColor(R.color.increasing_color));
            tvWbPhoto.setTextColor(JfResourceUtil.getSkinColor(R.color.increasing_color));
            tvWbPrice.setTextColor(JfResourceUtil.getSkinColor(R.color.increasing_color));
        } else if (btckanDetailBean.getTrendType() == -1) {
            tvRmbPrice.setTextColor(JfResourceUtil.getSkinColor(R.color.decreasing_color));
            tvRmbPhoto.setTextColor(JfResourceUtil.getSkinColor(R.color.decreasing_color));
            tvWbPhoto.setTextColor(JfResourceUtil.getSkinColor(R.color.decreasing_color));
            tvWbPrice.setTextColor(JfResourceUtil.getSkinColor(R.color.decreasing_color));
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item) {
        if (getUserVisibleHint()) {
            int clickedItemPosition = item.getOrder();
            String marketId;
            if (clickedItemPosition == 3000) {
                marketId = topItemMarketId;
            } else {
                marketId = btckanDetailBeans.get(clickedItemPosition).getMarketId();
            }
            long id = SelfSelectUtils.getIsSelectedId(marketId);
            if (id != -1) {
                SelfSelectedBean selfSelectedBean = new SelfSelectedBean();
                selfSelectedBean.setUserName(EnvironmentVariable.getUserName());
                selfSelectedBean.setMarketId(marketId);
                selfSelectedBean.setId(id);
                DaoSessionUtil.getInstance().getSelfSelectedBeanDao()
                        .delete(selfSelectedBean);
            } else {
                SelfSelectedBean selfSelectedBean = new SelfSelectedBean();
                selfSelectedBean.setMarketId(marketId);
                selfSelectedBean.setUserName(EnvironmentVariable.getUserName());
                DaoSessionUtil.getInstance().getSelfSelectedBeanDao()
                        .insert(selfSelectedBean);
            }
            EventBus.getDefault().postSticky(new SelfSelectRefreshEvent());
            return true;
        }
        return false;
    }

}
